//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.ComponentModel;
using System.Linq;
using System.Transactions;
using P2.Cuberry.Framework.BOLBase;
using P2.Cuberry.Framework.Helper;
using P2.Cuberry.Framework.Helper.Configuration;
using P2.Cuberry.Framework.Security;
using P2.Cuberry.Modules.Clinicom.BedList.DAL;


namespace P2.Cuberry.Modules.Clinicom.BedList.BusinessEntities
{
    public class BedList : BizObject, INotifyPropertyChanged
    {

        #region Members

        //++KeyID
        int _bedID = -1;
        public int BedID
        {
            get { return _bedID; }
            protected set
            {
                if (_bedID != value)
                {
                    _bedID = value;
                }
            }
        }


        string _bedNr = String.Empty;
        public string BedNr
        {
            get { return _bedNr; }
            protected set
            {
                if (_bedNr != value)
                {
                    _bedNr = value;
                    Modified = true;
                }
            }
        }

        //Add++
        string _room = String.Empty;
        public string Room
        {
            get { return _room; }
            set
            {
                if (value != _room)
                {
                    _room = value;
                    Modified = true;
                }
            }
        }

        string _status = String.Empty;
        public string Status
        {
            get { return _status; }
            set
            {
                if (value != _status)
                {
                    _status = value;
                    Modified = true;
                }
            }
        }

        string _category = String.Empty;
        public string Category
        {
            get { return _category; }
            set
            {
                if (value != _category)
                {
                    _category = value;
                    Modified = true;
                }
            }
        }

        int? _accountNr = null;
        public int? AccountNr
        {
            get { return _accountNr; }
            set
            {
                if (value != _accountNr)
                {
                    _accountNr = value;
                    Modified = true;
                }
            }
        }

        bool _companion = false;
        public bool Companion
        {
            get { return _companion; }
            set
            {
                if (value != _companion)
                {
                    _companion = value;
                    Modified = true;
                }
            }
        }

        int? _stockNr = null;
        public int? StockNr
        {
            get { return _stockNr; }
            set
            {
                if (value != _stockNr)
                {
                    _stockNr = value;
                    Modified = true;
                }
            }
        }

        int? _floor = null;
        public int? Floor
        {
            get { return _floor; }
            set
            {
                if (value != _floor)
                {
                    _floor = value;
                    Modified = true;
                }
            }
        }




        //DDL++



        #endregion


        #region Computed Properties
        //DDL++


        #endregion


        #region Constructors

        public BedList()
        {
            Modified = false;
        }


        public BedList(string keyBedNr)
        {
            this._bedNr = keyBedNr;
            FillMyObject();
            Modified = false;
        }


        public BedList(DAL.BedList beDList)
        {
            Load(beDList);
        }

        #endregion


        #region Read Operations

        //load an existing Instance
        public void Load(string keyBedNr)
        {
            BedNr = keyBedNr;
            if (keyBedNr == "")
            {
                FillMyObject();
            }
            else
            {
                Load("");
            }
            Modified = false;
        }


        //Add++ //DDL++
        public void Load(DAL.BedList sourceEntity)
        {
            if (sourceEntity != null)
            {
                this.BedNr = sourceEntity.BedNr;

                this.Room = sourceEntity.Room;
                this.Status = sourceEntity.Status;
                this.Category = sourceEntity.Category;
                this.AccountNr = sourceEntity.AccountNr;
                this.Companion = sourceEntity.Companion;
                this.StockNr = sourceEntity.StockNr;
                this.Floor = sourceEntity.Floor;

                //Default Fields                
                this.CreatedBy = sourceEntity.CreatedBy;
                this.CreatedOn = sourceEntity.CreatedOn;
                this.EditedBy = sourceEntity.EditedBy;
                this.EditedOn = sourceEntity.EditedOn;
                this.Timestamp = sourceEntity.TStamp;
                this.StatusID = sourceEntity.StatusID.GetValueOrDefault(P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName).StatusID);
            }
            else
            {
                this.BedNr = "";

                this.Room = String.Empty;
                this.Status = String.Empty;
                this.Category = String.Empty;
                this.AccountNr = null;
                this.StockNr = null;
                this.Floor = null;

                //Default Fields
                this.CreatedBy = String.Empty;
                this.EditedBy = String.Empty;
                P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus initStatus = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName);
                this.StatusID = initStatus.StatusID;
            }
            Modified = false;
        }


        internal P2TransactionMessage FillMyObject()
        {
            P2TransactionMessage tMsg = new P2TransactionMessage();
            if (this._bedNr == "")
            {
                Load(this._bedNr);
                return tMsg;
            }

            try
            {
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Clinicom", Properties.Settings.Default.EntityResources);
                using (BedListDataContext db = new BedListDataContext(connectionString))
                {
                    var xElements = from xElement in db.BedList
                                    where xElement.BedNr == this._bedNr
                                    select xElement;

                    foreach (var xElementx in xElements)
                    {
                        Load(xElementx);
                    }
                }

                tMsg.TransactionStatus = "green";
                tMsg.MessageText = "TMsg_FillMyObjectSuceeded";
            }
            catch (Exception ex)
            {
                tMsg.TransactionStatus = "red";
                tMsg.MessageText = "Error_Error";
                tMsg.MessageFreeText = ex.Message;
                P2ExceptionHandler.LogException(ex, this);
            }

            this.MessageStack.Add(tMsg);
            return tMsg;

        }
        #endregion


        #region Update Operations

        //Add++
        public P2MessageStack InsertAndUpdate(P2MessageStack MessageStack, bool checkDoublicate)
        {
            MessageStack.AddRange(this.Validator.Validate(this));

            try
            {
                if (MessageStack.StatusMessage.MessageStatus == P2ValidationStatus.green || MessageStack.StatusMessage.MessageStatus == P2ValidationStatus.white || (MessageStack.StatusMessage.MessageStatus == P2ValidationStatus.yellow && P2Validator.YellowErrorDialog.AskSave(MessageStack)))
                {
                    MessageStack.Clear();
                    string connectionString = ConfigurationSetUp.GetEntConnectionString("Clinicom", Properties.Settings.Default.EntityResources);

                    using (DAL.BedListDataContext db = new DAL.BedListDataContext(connectionString))
                    {
                        using (TransactionScope ts = new TransactionScope())
                        {
                            //Add++ //DDL++ //--> Set it to starting status.
                            if (this.StatusID == -1) this.StatusID = 3001;

                            if (string.IsNullOrEmpty(this.CreatedBy)) this.CreatedBy = User.Current.UserID;
                            this.EditedBy = User.Current.UserID;

                            DAL.BedList editedItem;
                            if (this.BedNr == "")
                            {
                                editedItem = new DAL.BedList()
                                {
                                    Room = this.Room,
                                    Status = this.Status,
                                    Category = this.Category,
                                    AccountNr = this.AccountNr,
                                    Companion = this.Companion,
                                    StockNr = this.StockNr,
                                    Floor = this.Floor,

                                    //Default Fields
                                    CreatedBy = User.Current.UserID,
                                    CreatedOn = DateTime.Now,
                                    EditedBy = User.Current.UserID,
                                    EditedOn = DateTime.Now,
                                    StatusID = this.StatusID
                                };
                                db.AddToBedList(editedItem);
                            }
                            else
                            {
                                editedItem = (from xItem in db.BedList
                                              where xItem.BedNr == this.BedNr
                                              select xItem).First();
                                if (editedItem.TStamp == this.Timestamp)
                                {
                                    //Add++ //DDL++
                                    editedItem.Room = this.Room;
                                    editedItem.Status = this.Status;
                                    editedItem.Category = this.Category;
                                    editedItem.AccountNr = this.AccountNr;
                                    editedItem.Companion = this.Companion;
                                    editedItem.StockNr = this.StockNr;
                                    editedItem.Floor = this.Floor;

                                    //Default Fields
                                    editedItem.EditedBy = User.Current.UserID;
                                    editedItem.EditedOn = DateTime.Now;
                                    editedItem.StatusID = this.StatusID;

                                    //track changes!
                                    this.SaveChangeLog(this.BedID);
                                }
                                else
                                {
                                    MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("TMsg_AccountNotUpdated"))); //--> rename it
                                }
                            }
                            if (MessageStack.StatusMessage.MessageStatus != P2ValidationStatus.red)
                            {
                                db.SaveChanges();
                                ts.Complete();
                                if (this.BedNr == "")
                                {
                                    MessageStack.Add(new P2TransactionMessage("green", P2Translator.GetResource("TMsg_BedListAdded")));
                                    this.BedNr = editedItem.BedNr;
                                }
                                else
                                    MessageStack.Add(new P2TransactionMessage("green", P2Translator.GetResource("TMsg_BedListUpdated")));
                            }
                        }
                    }

                    FillMyObject();
                    Modified = false;
                }
            }
            catch (Exception ex)
            {
                MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("Error_Error")));
                P2ExceptionHandler.LogException(ex, this);
            }
            return MessageStack;
        }

        #endregion


        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;


        private void OnPropertyChanged(string propertyName)
        {
            Modified = true;
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) Handler(this, new PropertyChangedEventArgs(propertyName));
        }

        //Add++ //DDL++
        public void OnAllPropertiesChanged()
        {
            OnPropertyChanged("BedNr");

            OnPropertyChanged("Room");
            OnPropertyChanged("Status");
            OnPropertyChanged("Category");
            OnPropertyChanged("AccountNr");
            OnPropertyChanged("Companion");
            OnPropertyChanged("StockNr");
            OnPropertyChanged("Floor");




            //Standard Fields
            OnPropertyChanged("StatusName");
            OnPropertyChanged("StatusID");
        }

        #endregion


        #region Validator

        public override P2Validator Validator
        {
            get
            {
                if (_validator == null)
                    _validator = new P2Validator(Properties.Settings.Default.ModuleName, this.EntityName, "BedNr", this);
                return _validator;
            }
        }

        #endregion


    }
}

